//
//  ForumVC.m
//  sensen_ios
//
//  Created by pro on 16/3/1.
//  Copyright © 2016年 pro. All rights reserved.
//

#import "ForumVC.h"




// 控制器
#import "PostDetailVC.h" // 帖子详情
#import "ForumSectionVC.h" // 论坛版块分类页面
#import "SearchPostVC.h" // 搜索界面
#import "ShopMessageVC.h"
//#import "PersonalSettingVC.h"
//#import "ForumHomeVC.h"
#import "WaterForumSectionVC.h"
//#import "PostVC.h"
// 视图
#import "CarouselView.h" // 轮播视图
#import "HomeSectionView.h" // 分栏视图

// 单元格
#import "PostBrowseCell.h" // 帖子概览单元格

@interface ForumVC () <UITableViewDataSource, UITableViewDelegate>
{
    UIScrollView *_scrollView; // 滑动视图
    
    CarouselView *_carouselView; // 顶部的图片视图
    HomeSectionView *_recruitModeratorView; // 招募版主视图
    HomeSectionView *_postAndCouponsView; // 发帖送券视图
    HomeSectionView *_showAndAwardView; // 晒图评奖视图
    UITableView *_tableView; // 表视图
}

@property (nonatomic, strong) NSMutableArray *itemsAry;

@end

@implementation ForumVC

#pragma mark - 视图方法
- (void)viewDidLoad {
    [super viewDidLoad];
    if (_itemsAry == nil) {
        _itemsAry = [[NSMutableArray alloc] init];
    }else{
        [_itemsAry removeAllObjects];
    }
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"休闲论坛";
    
    // 创建导航栏视图
    [self createRightBarButtonItems]; // 右侧搜索和消息
    [self createLeftBarButtonItems]; // 左侧返回，头像和发表
    
    // 创建
    [self _createViews];
    [self _getCarouselImgs];
    [self _initData]; // 获取数据
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    // 显示标签栏
    MainTabBarController *main = (MainTabBarController *)self.tabBarController;
    [main showTabBar];
   
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    // 隐藏标签栏
//    MainTabBarController *main = (MainTabBarController *)self.tabBarController;
//    [main hideTabBar];
}

#pragma mark - 获取数据
- (void)_getCarouselImgs {
    // 获得轮播图
    NSDictionary *params = @{@"position" : @6057};
    [BoyeHttpClient post:@"BY_Picture_getURL" apiVerson:100 params:params success:^(AFHTTPRequestOperation *operation, id result) {
        // 轮播图不为空
        if (![result isKindOfClass:[NSNull class]]) {
            NSMutableArray *ary = [NSMutableArray array];
            for (NSDictionary *dic in result) {
                CarouselModel *model = [[CarouselModel alloc] initContentWithDic:dic];
                
                [ary addObject:model];
            }
            
            // 设置轮播图
            _carouselView.modelAry = ary;
        }
        // 轮播图为空
        else {
            // 轮播图为空，则传入一个元素的数组，让轮播图加载默认图片
            _carouselView.modelAry = nil;
        }

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        // 失败
        [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",error.domain] withDuration:2];
    }];
}


- (void)_initData {
    
    self.view.userInteractionEnabled = NO;
    [SVProgressHUD showWithStatus:nil];
    [BoyeHttpClient post:@"BY_ForumForum_query" apiVerson:100 params:nil success:^(AFHTTPRequestOperation *operation, id result) {
        if(![result[@"list"] isKindOfClass:[NSNull class]]){
            NSMutableArray *array = [[NSMutableArray alloc] init];
            array = [result[@"list"] mutableCopy];
            [array removeObjectAtIndex:2];
            NSLog(@"%@",array);
            for (NSDictionary *resultDic in array) {
                PostModel *model = [[PostModel alloc] initContentWithDic:resultDic];
                PostCellFrameLayout *layout = [[PostCellFrameLayout alloc] init];
                layout.cellType = ZKCellBrowse;
                layout.model = model;
                [_itemsAry addObject:layout];
            }
            CGFloat tableHeight = 0;
            for (PostCellFrameLayout *layout in _itemsAry) {
                tableHeight += (kHeaderHeight + layout.cellRect.size.height);
            }
            _tableView.height = tableHeight;
            // 遍历滑动视图的子视图，设置滑动范围
            
            _scrollView.contentSize = CGSizeMake(0, _tableView.bottom);
        }
        [_tableView reloadData];
        
        self.view.userInteractionEnabled = YES;
        [SVProgressHUD dismiss];

        
        
 } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"加载失败" withDuration:1.5];
        self.view.userInteractionEnabled = YES;

 }];
   

}



#pragma mark - 创建视图
#pragma mark -- 创建导航栏视图 --
// 创建导航栏右侧按钮（搜索和消息）
- (void)createRightBarButtonItems {
    
    NSArray *imgNames = @[@"论坛首页_消息通知", @"论坛首页_搜索"];
    NSMutableArray *items = [NSMutableArray array];
    for (int i = 0; i < imgNames.count; i ++) {
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0, 0, 20, 20);
        [button setBackgroundImage:[UIImage imageNamed:imgNames[i]] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(_naviRightAction:) forControlEvents:UIControlEventTouchUpInside];
        button.tag = i + 1;
        
        UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
        [items addObject:barButtonItem];
    }
    
    self.navigationItem.rightBarButtonItems = items;
}
// 创建导航栏左侧按钮
- (void)createLeftBarButtonItems {
    
    // 返回
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(0, 0, 25/2, 43/2);
    [backButton setBackgroundImage:[UIImage imageNamed:@"导航栏_返回"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(_naviLeftAction:) forControlEvents:UIControlEventTouchUpInside];
    backButton.tag = 1;
    
//    // 头像
//    UIImageView *iconImgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
//    UIImage *img = [UIImage imageWithColor:rgba(12, 91, 158, 1)];
//    img = [img createRoundedRectImage:CGSizeMake(30, 30)];
//    iconImgView.image = img;
//    UserModel *user = [CommonCache getUserInfo];
//    if (user != nil) {
//        NSURL * url = [[NSURL alloc]initWithString:user.head];
//        [iconImgView setImageWithURL: url placeholderImage:[UIImage imageNamed:@"defaultImage"]];
//    }else{
//        iconImgView.hidden = YES;
//    }
//    iconImgView.userInteractionEnabled = YES;
//    iconImgView.layer.cornerRadius = 15;
//    iconImgView.clipsToBounds = YES;
//    iconImgView.tag = 2;
//    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(_iconTap:)];
//    [iconImgView addGestureRecognizer:tap];
    
    UIBarButtonItem *barButtonItem1 = [[UIBarButtonItem alloc] initWithCustomView:backButton];
//    UIBarButtonItem *barButtonItem2 = [[UIBarButtonItem alloc] initWithCustomView:iconImgView];

    
    self.navigationItem.leftBarButtonItems = @[barButtonItem1];
}

#pragma mark -- 创建子视图 --
- (void)_createViews {
    
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64)];
    _scrollView.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1];
    _scrollView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:_scrollView];
    
    [self _createTopViews]; // 顶部视图，
    [self _initTableView]; // 表视图
    
    // 遍历滑动视图的子视图，设置滑动范围
    UIView *lastView = _scrollView.subviews.lastObject;
    _scrollView.contentSize = CGSizeMake(0, lastView.bottom);
    
}
- (void)_createTopViews {
    
    CGFloat x, y, width, height;
    
    // 顶部视图
    x = 0;
    y = 0;
    width = SCREEN_WIDTH;
    height = width / 2;
    _carouselView = [[CarouselView alloc] initWithFrame:CGRectMake(x, y, width, height) timerDuration:3 carouselAmount:3];
    [_scrollView addSubview:_carouselView];
    
    // 森森智囊团
    x = 5;
    y = _carouselView.bottom + 5;
    width = (SCREEN_WIDTH - 3 * x) / 2; // 有三个间隙
    height = width / 2;
    _recruitModeratorView = [[HomeSectionView alloc] initWithFrame:CGRectMake(x, y, width, height) type:ZKHomeSectionViewTypeH];
    _recruitModeratorView.backgroundColor = rgba(230, 230, 230, 1);
    _recruitModeratorView.title = @"森森智囊团";
    _recruitModeratorView.imgName = @"论坛首页_森森智囊团1";
    _recruitModeratorView.titleColor = rgba(36, 179, 40, 1);
    [_scrollView addSubview:_recruitModeratorView];
    UITapGestureRecognizer *recruitModeratorTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(_recruitModeratorAction:)];
    [_recruitModeratorView addGestureRecognizer:recruitModeratorTap];

    // 疯享排行榜
    y = _recruitModeratorView.bottom + 5;
    _postAndCouponsView = [[HomeSectionView alloc] initWithFrame:CGRectMake(x, y, width, height) type:ZKHomeSectionViewTypeH];
    _postAndCouponsView.backgroundColor = rgba(230, 230, 230, 1);
    _postAndCouponsView.title = @"森森采购师";
    _postAndCouponsView.imgName = @"论坛首页_疯享排行榜";
    _postAndCouponsView.titleColor = rgba(255, 76, 103, 1);
    [_scrollView addSubview:_postAndCouponsView];
    UITapGestureRecognizer *postAndCouponsTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(_postAndCouponsAction:)];
    [_postAndCouponsView addGestureRecognizer:postAndCouponsTap];
    
    // 人人爱设计
    x = _recruitModeratorView.right + 5;
    y = _recruitModeratorView.top;
    height = _recruitModeratorView.height * 2 + 5;
    _showAndAwardView = [[HomeSectionView alloc] initWithFrame:CGRectMake(x, y, width, height) type:ZKHomeSectionViewTypeV2];
    _showAndAwardView.backgroundColor = rgba(230, 230, 230, 1);
    _showAndAwardView.title = @"森森设计师";
    _showAndAwardView.imgName = @"论坛首页_人人爱设计";
    _showAndAwardView.titleColor = rgba(0, 149, 229, 1);
    [_scrollView addSubview:_showAndAwardView];
    UITapGestureRecognizer *showAndAwardTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(_showAndAwardAction:)];
    [_showAndAwardView addGestureRecognizer:showAndAwardTap];

}

// 创建表视图
- (void)_initTableView {
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, _showAndAwardView.bottom, SCREEN_WIDTH, 0) style:UITableViewStyleGrouped];
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.scrollEnabled = NO;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_scrollView addSubview:_tableView];
    
    
    
    // 设置表视图高度
//    _tableView.height = (kCellHeight + kHeaderHeight) * sections;
    
    // 注册单元格
    [_tableView registerClass:[PostBrowseCell class] forCellReuseIdentifier:@"PostBrowseCell"];
}

#pragma mark - UITableViewDataSource UITableViewDelegate
// 设置组数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _itemsAry.count;
}
// 设置行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}
// 设置单元格属性
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    PostBrowseCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PostBrowseCell"];
    
    // 填充数据
    PostCellFrameLayout *layout = _itemsAry[indexPath.section];
    cell.layout = layout;
    
    return cell;
    
}
// 设置单元格行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    PostCellFrameLayout *layout = _itemsAry[indexPath.section];
    return layout.cellRect.size.height;
}
// 设置组尾高度
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 1;
}
// 设置组头高
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return kHeaderHeight;
}
// 设置组头视图
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *basalView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, kHeaderHeight)];
    basalView.backgroundColor = [UIColor clearColor];
    basalView.tag = section;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(_headerTap:)];
    [basalView addGestureRecognizer:tap];

    // 竖线
    UIImageView *lineImgView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 0, 2, 15)];
    lineImgView.image = [UIImage imageNamed:@"论坛首页_蓝色竖线"];
    [basalView addSubview:lineImgView];
    lineImgView.center = CGPointMake(lineImgView.center.x, kHeaderHeight / 2);
    
    // 标题
    CGFloat x = lineImgView.right + 5;
    CGFloat y = 0;
    CGFloat width = 100;
    CGFloat height = kHeaderHeight;
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
    titleLabel.font = FONT(15);
    titleLabel.text = @"ffsdf";
    titleLabel.textColor = SS_NAVI_BLUE_COLOR;
    titleLabel.textAlignment = NSTextAlignmentLeft;
    [basalView addSubview:titleLabel];
    
    // 右侧箭头
    width = 10;
    height = 15;
    x = SCREEN_WIDTH - 10 - width;
    UIImageView *enterImgView = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, width, height)];
    enterImgView.image = [UIImage imageNamed:@"论坛首页_进入论坛"];
    [basalView addSubview:enterImgView];
    enterImgView.center = CGPointMake(enterImgView.center.x, kHeaderHeight / 2);
    
    // 进入论坛label
    width = 100;
    height = kHeaderHeight;
    y = 0;
    UILabel *enterLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
    enterLabel.font = FONT(15);
    enterLabel.text = @"进入论坛";
    enterLabel.textColor = RED_COLOR;
    enterLabel.textAlignment = NSTextAlignmentRight;
    [basalView addSubview:enterLabel];
    enterLabel.right = enterImgView.left - 5;
    
    PostCellFrameLayout *layout = [[PostCellFrameLayout alloc] init];
    layout = _itemsAry[section];
    titleLabel.text = layout.model.name;
    
    return basalView;
}

// 单元格点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//    if (indexPath.section == 0) {
//
//        vc.fid = _layout1.model.fid;
//        vc.tid = _layout1.model.tid;
//        [self.navigationController pushViewController:vc animated:YES];
//    }else if(indexPath.section == 1){
//        PostDetailVC *vc = [[PostDetailVC alloc] init];
//        vc.fid = _layout2.model.fid;
//        vc.tid = _layout2.model.tid;
//        [self.navigationController pushViewController:vc animated:YES];
//    }
    PostDetailVC *vc = [[PostDetailVC alloc] init];
    PostCellFrameLayout *layout = _itemsAry[indexPath.section];
    vc.fid = layout.model.fid;
    vc.tid = layout.model.tid;
    [self.navigationController pushViewController:vc animated:YES];
}






#pragma mark - 点击事件
// 导航栏右侧按钮（搜索和消息通知）
- (void)_naviRightAction:(UIButton *)button {
    switch (button.tag) {
        case 1:
        {
            //消息页的跳转
            ShopMessageVC *vc = [[ShopMessageVC alloc] init];
//            [self.navigationController pushViewController:vc animated:YES];
//            ForumHomeVC *vc = [[ForumHomeVC alloc] init];
//            WaterForumSectionVC *vc = [[WaterForumSectionVC alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case 2:
        {
            SearchPostVC *vc = [[SearchPostVC alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
            
        default:
            break;
    }
}
// 导航栏左侧按钮（返回和发表）
- (void)_naviLeftAction:(UIButton *)button {
    // 返回
    if (button.tag == 1) {
        [self leftAction:nil];
    }
}
// 导航栏左侧头像按钮
//- (void)_iconTap:(UITapGestureRecognizer *)tap {
//    UserModel *user = [CommonCache getUserInfo];
//    if (user == nil) {
//        LoginVC *vc = [[LoginVC alloc] init];
//        BaseNavVC *naviVc = [[BaseNavVC alloc] initWithRootViewController:vc];
//        [self presentViewController:naviVc animated:YES completion:nil];
//    }else{
////        PersonalSettingVC *vc = [[PersonalSettingVC alloc] init];
////        [self.navigationController pushViewController:vc animated:YES];
//        PostVC *vc = [[PostVC alloc] init];
//        [self.navigationController pushViewController:vc animated:YES];
//    }
//}
// 森森智囊团
- (void)_recruitModeratorAction:(UITapGestureRecognizer *)tap {
//    PostDetailVC *vc = [[PostDetailVC alloc] init];
//    vc.title =@"森森智囊团";
//    vc.tid = @"ssznt";
//    vc.fid = @"0";
//    [self.navigationController pushViewController:vc animated:YES];
    ForumSectionVC *vc = [[ForumSectionVC alloc] init];
    vc.naviTitle = @"森森智囊团";
    vc.fid = @"3";
    [self.navigationController pushViewController:vc animated:YES];
}
// 森森设计师
- (void)_showAndAwardAction:(UITapGestureRecognizer *)tap {
//    PostDetailVC *vc = [[PostDetailVC alloc] init];
//    vc.title =@"森森设计师";
//    vc.tid = @"rrasj";
//    vc.fid = @"0";
//    [self.navigationController pushViewController:vc animated:YES];
    ForumSectionVC *vc = [[ForumSectionVC alloc] init];
    vc.naviTitle = @"森森设计师";
    vc.fid = @"8";
    [self.navigationController pushViewController:vc animated:YES];

}
// 森森采购师
- (void)_postAndCouponsAction:(UITapGestureRecognizer *)tap {
//    PostDetailVC *vc = [[PostDetailVC alloc] init];
//    vc.title = @"森森采购师";
//    vc.tid = @"fxphb";
//    vc.fid = @"0";
//    [self.navigationController pushViewController:vc animated:YES];
    ForumSectionVC *vc = [[ForumSectionVC alloc] init];
    vc.naviTitle = @"森森采购师";
    vc.fid = @"7";
    [self.navigationController pushViewController:vc animated:YES];
}
// 点击组头进入论坛版块分类页面
- (void)_headerTap:(UITapGestureRecognizer *)tap {
    ForumSectionVC *vc = [[ForumSectionVC alloc] init];
    PostCellFrameLayout *layout = _itemsAry[tap.view.tag];
    vc.fid = layout.model.fid;
    vc.naviTitle = layout.model.name;
    [self.navigationController pushViewController:vc animated:YES];
}


@end
